import request from './request'

// 登录管理
const auth = {
	// 微信H5登录
	wxH5Login(loginType = 'login') {
		return new Promise((resolve, reject) => {
			const code = this.getUrlParam('code')
			console.log('code: ' + code)
			const state = this.getUrlParam('state')
			const alias = uni.getStorageSync('alias')
			const appid = uni.getStorageSync(alias + '_wx_appid')

			if (!alias) {
				uni.showModal({
					title: '提示',
					content: '无效的访问链接，请重新打开',
					showCancel: false
				})
				reject(new Error('无效的访问链接'))
				return
			}

			// 清除URL中的code和state参数
			const url = new URL(window.location.href)
			url.searchParams.delete('code')
			url.searchParams.delete('state')
			window.history.replaceState({}, '', url.toString())

			if (!code) {
				if (loginType === 'login') {
					uni.showToast({
						title: uni.getStorageSync(alias + '_token') ? '登录失效，即将重新登录' : '未登录，即将登录',
						icon: 'none'
					})
				}

				// 从URL中提取页面路径和参数
				const url = new URL(window.location.href)
				const hash = url.hash.substring(1) // 去掉#号
				
				// 提取页面路径和参数
				let fullPath = ''
				if (hash) {
					fullPath = hash.startsWith('/') ? hash.substring(1) : hash
				}
				
				if (fullPath) {
					uni.setStorageSync(alias + '_original_page', '/' + fullPath)
				}

				// 重定向到微信授权页面
				const redirectUri = window.location.href

				console.log('重定向前页面：' + redirectUri)
				let scope = 'snsapi_userinfo'
				// if (loginType === 'login') {
				// 	scope = 'snsapi_base'
				// }
				window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${loginType}#wechat_redirect`
				return
			}

			// 有code则调用后端登录接口
			request({
				url: '/wechat/auth/getUser',
				data: {
					code,
					alias,
					loginType: state
				}
			}).then(res => {
				if (res.code === 0) {
					if (loginType === 'login') {
						console.log('获取到Token: ' + res.data.token)
						uni.setStorageSync(alias + '_token', res.data.token)

						uni.showToast({
							title: '登录成功，即将跳转',
							icon: 'none'
						})
					}

					// 获取原始访问页面
					const originalPage = uni.getStorageSync(alias + '_original_page')
					if (originalPage) {
						uni.removeStorageSync(alias + '_original_page')
						uni.navigateTo({
							url: originalPage
						})
					} else {
						uni.navigateTo({
							url: '/pages/index/index'
						})
					}
				} else {
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
					if (res.message === 'openid获取失败') {
						const redirectUri = window.location.href
						let scope = 'snsapi_userinfo'
						window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${loginType}#wechat_redirect`
					}
				}
				resolve(res)
			}).catch(reject)
		})
	},

	// 获取url参数
	getUrlParam(name) {
		const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
		const r = window.location.search.substr(1).match(reg)
		if (r != null) return decodeURIComponent(r[2])
		return null
	}
}

export default auth 